package examples.books.backend

import groovy.transform.CompileStatic

import javax.inject.Singleton
import java.util.function.Consumer
import java.util.stream.Stream

/**
 * Created by Misty on 2015/6/4.
 */
@CompileStatic
@Singleton
class LibraryServiceMockImpl implements LibraryService {
    private Set<Book> books = new HashSet<>()

    public void addBooks(Book... books) {
        Stream.of(books).each { Book b -> this.books << b }
    }

    public void addSomeBooks() {
        this.addBooks(
                new Book("/1", "A Game of Thrones", "Georg R. R. Martin", "First part of SOIF"),
                new Book("/2", "A Clash of Kings", "Georg R. R. Martin", "Second part of SOIF"),
                new Book("/3", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/4", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/5", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/6", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/7", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/8", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/9", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/10", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/11", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/12", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/13", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/14", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/15", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/16", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/17", "A Storm of Swords", "Georg R. R. Martin", "Third part of SOIF"),
                new Book("/18", "The Metamorphosis", "Franz Kafka", "A man turns into an insect")
        );
    }

    @Override
    List<Book> search(String query, Consumer<Error> errorCallback) {
        if (query == null || query.isEmpty()) {
            return books.collect { b -> new Book(b.href, b.title, b.author, null) }
                    .sort { a, b -> a.title.compareTo(b.title) }
        } else {
            return books.findAll { it.title.contains(query) }
                    .collect { b -> new Book(b.href, b.title, b.author, null) }
                    .sort { a, b -> a.title.compareTo(b.title) }
        }
    }

    @Override
    Book showDetails(Book book, Consumer<Error> errorCallback) {
        return books.find { b -> b.href.equals(book.href) }
    }
}
